package org.ccay.i18n;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Properties;

import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.Assert;


/**
 * 此类暂保留共后期国际化优化使用，暂时提供内存Map全量缓存机制处理
 * 重写ReloadableResourceBundleMessageSource，提供数据库加载国际化的支持
 * @author chaowangbang
 *
 */
public class ResourceBundleMessageSource extends ReloadableResourceBundleMessageSource{
	

	/**
	 * 通过数据库加载国际化的文件代号
	 */
	public static final String DB_FILENAME ="CCAY_I18N_T";
	
	public ResourceBundleMessageSource(){
		// 查找classpath上的config/*_i18n*.properties文件配置
		ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
		Resource[] resources;
		try {
			resources = resourcePatternResolver
					.getResources("classpath*:config/i18n.*.properties");
			List<String> beannames = new ArrayList<String>();
			for (Resource resource : resources) {
				String fileName = resource.getFilename(); 
				beannames.add("classpath:config/"+fileName.substring(0,fileName.indexOf("_")));
			}
			beannames.add("CCAY_I18N_T");
			super.setBasenames(beannames.toArray(new String[0]));
		} catch (IOException ioe) {
			logger.error(ioe);
		}
	}
	
	
	/**
	 * 支持的语言
	 */
	protected Locale[] supportLanguages = new Locale[0];
	
	
	/**
	 * 获取支持的
	 * @return
	 */
	public Locale[] getSupportLanguages() {
		return supportLanguages;
	}
	

	/**
	 * 设置支持的语言
	 * @param languages
	 */
	public void setSupportLanguages(String... languages) {
		if (languages != null) {
			supportLanguages = new Locale[languages.length];
			for (int i = 0; i < languages.length; i++) {
				String language = languages[i];
				Assert.hasText(language, "languages must not be empty");
				String languageParams[] = language.split("_");
				this.supportLanguages[i] = new Locale(languageParams[0],languageParams[1]);
			}
		}
		else {
			this.supportLanguages = new Locale[0];
		}
	}
	
	
	@Override
	protected PropertiesHolder refreshProperties(String filename, PropertiesHolder propHolder) {
		if(filename.startsWith(DB_FILENAME)){
			String language = getLanguageFromFileName(filename);
			//忽略默认语言
			if(language == null){
				return new PropertiesHolder();
			}
			Properties props = loadProperties(filename);
			if (logger.isDebugEnabled()) {
				logger.debug("Re-cached "+props.size()+" properties for database.");
			}
			PropertiesHolder propertiesHolder =  new PropertiesHolder(props,-1);
			return propertiesHolder;
		}
		return super.refreshProperties(filename,propHolder);
	}
	
	/**
	 * 仅需要支持语言+国家的情况
	 */
	@Override
	protected List<String> calculateFilenamesForLocale(String basename, Locale locale) {
		List<String> result = new ArrayList<String>(3);
		String language = locale.getLanguage();
		String country = locale.getCountry();
		
		StringBuilder temp = new StringBuilder(basename);
		temp.append('_');
		if (language.length() > 0) {
			temp.append(language);
		}

		temp.append('_');
		if (country.length() > 0) {
			temp.append(country);
			result.add(temp.toString());
		}

		return result;
	}
	
	/**
	 * 从数据库中加载查询国际化信息
	 * @param filename
	 * @return
	 */
	private String getLanguageFromFileName(String filename) {
		for(Locale locale : getSupportLanguages()){
			String localStr = locale.getLanguage()+"_"+locale.getCountry();
			if(filename.endsWith(localStr)){
				return localStr;
			}
		}
		return null; 
	}
	
	private Properties loadProperties(String language) {
		//TODO 从数据库加载
		Properties ps = new Properties();
		ps.put("test.0003", "来自数据库的测试");
		return ps;
		
	}
	
}
